/* global 
   global:false  
*/ 
import $fetch from '@system.fetch'
import {$utils} from '../helper'
const hook2global = global.__proto__ || global
const delayTime=10000 //超时时间
function requestHandle(_params) {
  let param={}
  let commonParam = hook2global.$commonData
  param=_params

  if(param.data&&!param.data.isBi){
    let postData=Object.assign(param.data,commonParam)
    let sign=$utils.getSign(postData)
    param.data.sign=sign
  }

  if(_params.method=='get'){
    param.url=queryString(_params.url, commonParam)
  }else{
    let postData=Object.assign(param.data,commonParam)
    if(param.data&&!param.data.list){
      param.data=postData 
    }
  }
  
  return new Promise((resolve, reject) => {
    let timer=null
    $fetch
      .fetch({
        url: hook2global.$originUrl+param.url ,
        method: param.method,
        data:param.data
      })
      .then(response => {
        const content = JSON.parse(response.data.data)
        // console.log("request success",content)
        /* @desc: 可跟具体不同业务接口数据，返回你所需要的部分，使得使用尽可能便捷 */
        if(timer){
          clearTimeout(timer)
          timer=null
        }
        resolve(content)
      })
      .catch((error, code) => {
        console.log(`request fail code = ${code} url=${param.url}`)
        if(timer){
          clearTimeout(timer)
          timer=null
        }
        reject(error)
      })
    timer=setTimeout(()=>{
      reject()
    },delayTime)
  })
}
/* 此处只是处于示例代码的可运行性，实际项目中，此方法最好予以封装 & 提取 */
function queryString(url, query) {
  let str = []
  let token=''
  for (let key in query) {
    if (typeof query[key] === 'object') {
      query[key] = JSON.stringify(query[key])
    }
    if(key=='token'){
      token=encodeURIComponent(query[key])
    }
    let urlParams=$utils.getUrlParams(url)
    if(!urlParams[key]){
      if(key=='token'){ 
        str.push(key + '=' + token)
      }else{
        str.push(key + '=' + query[key])
      }
    }
  }
  let paramStr = str.join('&')
  return paramStr ?`${url}${url.indexOf('?')!=-1?'&':'?'}${paramStr}`: url
}
export default {
  post: function(url, params) {
    return requestHandle({
      method: 'post',
      url: url,
      data: params?params:{}
    })
  },
  get: function(url, params,header) {
    return requestHandle({
      method: 'get',
      url: queryString(url, params?params:{}),
      header:header?header:null,
    })
  }
}
